//
//  JobDetailViewController2.m
//  CYWFrame
//
//  Created by 于顺燊 on 2018/10/27.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "JobDetailViewController.h"
#import "CompanyInfoDetailViewController.h"
#import "UIButton+EdgeInsets.h"

@interface JobDetailViewController ()

@property (weak, nonatomic) IBOutlet UILabel *jobName;
@property (weak, nonatomic) IBOutlet UIButton *workExp;
@property (weak, nonatomic) IBOutlet UIButton *education;

@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UILabel *welfare;
@property (weak, nonatomic) IBOutlet UIImageView *companyLogo;
@property (weak, nonatomic) IBOutlet UILabel *companyName;
@property (weak, nonatomic) IBOutlet UILabel *field;
@property (weak, nonatomic) IBOutlet UILabel *development;
@property (weak, nonatomic) IBOutlet UILabel *companySize;
@property (weak, nonatomic) IBOutlet UILabel *address;
@property (weak, nonatomic) IBOutlet UILabel *duty;
@property (weak, nonatomic) IBOutlet UILabel *demand;
@property (weak, nonatomic) IBOutlet UIImageView *publisherImg;
@property (weak, nonatomic) IBOutlet UILabel *publisher;
@property (weak, nonatomic) IBOutlet UILabel *publisherTitle;
@property (weak, nonatomic) IBOutlet UIButton *deliverBtn;

@property (strong, nonatomic)JobDetailInfo *model;
@property (strong, nonatomic) UIButton *collectBtn;
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *labelsToAdjust;
@property (weak, nonatomic) IBOutlet UIButton *returnToLive;
@property (weak, nonatomic) IBOutlet UILabel *salary;
@property (weak, nonatomic) IBOutlet UIView *companyView;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *btnsToAdjust;

@end

@implementation JobDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
	[self createUI];
	[self getDetailInfo];
}

- (void)createUI
{
	self.navigationItem.title = @"职位详情";
	if (self.shouldHideDeliverBtn) {
		self.deliverBtn.hidden = YES;
	}
	else {
		_collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
		[_collectBtn setBackgroundImage:IMAGE(@"job_icon_uncollect") forState:UIControlStateNormal];
		[_collectBtn setBackgroundImage:IMAGE(@"job_icon_collected") forState:UIControlStateSelected];
		[_collectBtn addTarget:self action:@selector(collectOrCancelCollect) forControlEvents:UIControlEventTouchUpInside];
		UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:_collectBtn];
		self.navigationItem.rightBarButtonItem = item;
		
		self.deliverBtn.backgroundColor = UIMainColorRGB;
		[self.deliverBtn addTarget:self action:@selector(deliverResume:) forControlEvents:UIControlEventTouchUpInside];
	}
	if (self.isFromLive) {
		[self.returnToLive addTarget:self action:@selector(returnTolive:) forControlEvents:UIControlEventTouchUpInside];
		self.returnToLive.tag = 99;
		self.returnToLive.hidden = NO;
		[self.view bringSubviewToFront:self.returnToLive];
	}
	[self.companyView addActionWithblock:^{
		[self jumpToCompanyDetail];
	}];
}

- (void)getDetailInfo
{
	NSDictionary *param = @{@"position_id" : self.position_id};
	[[NetworkTool sharedTool] requestWithName:@"获取职位详情" URLString:APIJobDetail parameters:param method:@"POST" callBack:^(id responseObject) {
		NSDictionary *dict = responseObject[@"data"];
		[self.model setValuesForKeysWithDictionary:dict];
		[self assignValue];
		if (self.model.collection_status == 1) {
			[self.collectBtn setSelected:YES];
		}
		else {
			[self.collectBtn setSelected:NO];
		}
	}];
}

- (void)deliverResume: (UIButton *)sender
{
	NSInteger role = [GetUserDefaule(USERINFO)[@"role"] integerValue];
	if (role == 3) {
		[self presentViewController:[LZCTools alertMessage:@"您目前是商家角色，请进行求职者认证后再次操作"] animated:YES completion:nil];
		return;
	}
	
	NSLog(@"i was hererererererer e2313");
	NSDictionary *param = @{@"position_id" : self.position_id};
	[[NetworkTool sharedTool] requestWithName:@"投递简历" URLString:APISendResume parameters:param method:@"POST" callBack:^(id responseObject) {
		NSString *resultState = responseObject[@"data"][@"status"];
		if ([resultState integerValue] == 1) {
			UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"投递成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
			[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
				[self.navigationController popViewControllerAnimated:YES];
			}]];
			[self presentViewController:alert animated:YES completion:nil];
		}
		
	}];
}

- (void)returnTolive:(UIButton *)sender {
	//[self dismissViewControllerAnimated:YES completion:nil];
	NSLog(@"i was called");
	[self.parentViewController removeChild:self];
}

- (JobDetailInfo *)model{
	if (!_model) {
		_model = [[JobDetailInfo alloc] init];
	}
	return _model;
}
- (void)collectOrCancelCollect {
	
	NSLog(@"i was herherherhehrehrher");
	NSInteger role = [GetUserDefaule(USERINFO)[@"role"] integerValue];
	if (role == 3) {
		[self presentViewController:[LZCTools alertMessage:@"您目前是商家角色，请进行求职者认证后再次操作"] animated:YES completion:nil];
		return;
	}
	
	NSDictionary *dict;
	NSString *url;
	
	if (self.collectBtn.isSelected) {
		url = APICancelCollectJobOrResume;
		dict = @{@"type":@"2",
				 @"position_ids":self.model.position_id
				 };
	}
	else {
		url = APICollectJobOrResume;
		dict = @{@"type":@"2",
				 @"position_id":self.model.position_id
				 };
	}
	[[NetworkTool sharedTool] requestWithName:@"收藏岗位" URLString:url parameters:dict method:@"POST" callBack:^(id responseObject) {
		NSString *status = responseObject[@"data"][@"status"];
		if ([status integerValue] == 1) {
			[self.collectBtn setSelected:!self.collectBtn.isSelected];
            if (self.collectBtn.isSelected) {
                [LZCTools HUDMessage:@"收藏成功" delay:1.0];
            }
            else {
                [LZCTools HUDMessage:@"已取消收藏" delay:1.0];
            }
		}
	}];
}

- (void)assignValue {
	self.jobName.text = self.model.category_title;
	self.salary.text = self.model.salary;
	[self.workExp setTitle:self.model.work_life forState:UIControlStateNormal];
	[self.education setTitle:self.model.education forState:UIControlStateNormal];
	
	//从字段中用空格隔开获取数组
	NSArray *welfareArr = [self.model.welfare componentsSeparatedByString:@"  "];
	CGFloat labelX = self.welfare.x;
	CGFloat labelY = self.welfare.y;
	self.welfare.hidden = YES;
	for(int i = 0; i<welfareArr.count; i++){
		NSString *welfareStr = welfareArr[i];
		//有可能最后有一个空格，跳过它不生成label
		if([NSString isEmpty:welfareStr]){
			continue;
		}
		CGSize labelSize = [LZCTools textSizeWithText:welfareStr font:[UIFont systemFontOfSize:12]];
		UILabel *welfareLabel = [[UILabel alloc] initWithFrame:CGRectMake(labelX, labelY, labelSize.width+5, labelSize.height+5)];
		welfareLabel.text = welfareStr;
		[welfareLabel setBackgroundColor:RGB(241, 243, 245)];
		[welfareLabel setTextColor:kGrayColor];
		welfareLabel.font = [UIFont systemFontOfSize:12];
		welfareLabel.textAlignment = NSTextAlignmentCenter;
		[self.topView addSubview:welfareLabel];
		labelX = welfareLabel.x+welfareLabel.width+5;
		NSLog(@"i = %d", i);
	}
	[self.companyLogo sd_setImageWithURL:[NSURL URLWithString:self.model.company_logo] placeholderImage:IMAGE(@"placeHolder")];
	self.companyName.text = self.model.company_title;
	self.field.text = self.model.industry_field;
	self.development.text = self.model.development;
	self.companySize.text = self.model.company_size;
	self.address.text = [NSString stringWithFormat:@"%@ %@", self.model.district, self.model.address];
	self.duty.text = self.model.duty;
	self.demand.text = self.model.demand;
	[self.publisherImg sd_setImageWithURL:[NSURL URLWithString:self.model.company_logo] placeholderImage:IMAGE(@"placeHolder")];
	self.publisher.text = self.model.publisher;
	self.publisherTitle.text = self.model.position;
	for (UILabel *label in self.labelsToAdjust){
		[label sizeToFit];
	}
	for (UIButton *btn in self.btnsToAdjust) {
		[btn layoutButtonWithEdgeInsetsStyle:ButtonEdgeInsetsStyleImageLeft imageTitlespace:5];
	}
}

- (void)jumpToCompanyDetail {
	CompanyInfoDetailViewController *detail = [[CompanyInfoDetailViewController alloc] init];
	detail.companyId = self.model.company_id;
	[self.navigationController pushViewController:detail animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
